package org.jash.shop2111.search

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.doOnTextChanged
import androidx.recyclerview.widget.SortedList
import androidx.recyclerview.widget.SortedListAdapterCallback
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import dagger.hilt.android.AndroidEntryPoint
import org.jash.shop2111.BR
import org.jash.shop2111.R
import org.jash.shop2111.databinding.ActivitySearchBinding
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.mvvm.BaseActivity
import org.jash.shop2111.utils.CommonAdapter

@Route(path = "/shop/search")
@AndroidEntryPoint
class SearchActivity : BaseActivity<ActivitySearchBinding, SearchViewModel>() {
    @Autowired
    @JvmField
    var key = ""
    val searchResult by lazy { SortedList(Goods::class.java, object :SortedListAdapterCallback<Goods>(adapter) {
        override fun compare(o1: Goods?, o2: Goods?): Int {
            return o1?.id?.minus(o2?.id ?: 0) ?: 0
        }

        override fun areContentsTheSame(oldItem: Goods?, newItem: Goods?): Boolean = oldItem == newItem

        override fun areItemsTheSame(item1: Goods?, item2: Goods?): Boolean = item1?.id == item2?.id

    }) }
    val adapter by lazy { SearchAdapter<Goods>({R.layout.goods_item to BR.goods}) }

    override fun initData() {
        ARouter.getInstance().inject(this)
        viewModel.goodsLiveData.observe(this) {
            searchResult.beginBatchedUpdates()
            searchResult.replaceAll(it)
            searchResult.endBatchedUpdates()
        }
        viewModel.search(key)
    }

    override fun initView() {
        adapter.data = searchResult
        binding.recycler.adapter = adapter
        binding.search.setText(key)
        binding.search.doOnTextChanged { text, _, _, _ ->
            if (!text.isNullOrEmpty()) {
                key = text.toString()
                viewModel.search(key)
            }
        }
    }
}